package me

import (
	"context"
	"image/color"
	"time"

	"fyne.io/fyne/v2"
	cv "fyne.io/fyne/v2/canvas"
	ct "fyne.io/fyne/v2/container"
	bd "fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/theme"
	. "fyne.io/fyne/v2/widget"
	fx "fyne.io/x/fyne/widget"
)

var (
	NumF, NumFd, NumH, Total = 0, 0, 0, 0
	SelFilter, SelSort       *Select
	FilterType               string
	SelectedPath             string
	BdFilterType             = bd.BindString(&FilterType)
	FnSort                   string
	BdRefreshDir             = bd.BindString(&FnSort)
	OptsFilter               = []string{"All", "只显示文件夹", "只显示文件",
		"只显示图片", "只显示音频", "只显示视频", "只显示压缩包"}
	OptsSort = []string{"文件夹在前", "文件在前", "图片在前", "Mp3First", "视频在前",
		"压缩包在前"}
	ExtImage = []string{".jpg", ".jpeg", ".png", ".bmp", ".tif"}
	ExtAudio = []string{".mp3", ".wav"}
	ExtVideo = []string{".mp4", ".avi"}
	ExtZip   = []string{".zip", ".rar", ".7z", ".gz"}
	ExtText  = []string{"txt", "go", "mod", "sum", "md", "json", "c", "cpp", "h", "hpp", "java"}

	FavoritesAdded          []string
	CvsNum, CvsMsg          *cv.Text
	CvsFileSize, CvsCharSet *cv.Text
	Red                     = color.RGBA{255, 0, 0, 255}
	BtnPaste, BtnReset      *Button
	BtnDelFavorite          *Button
	TxtEntry                *Entry
	FirstFn                 []func(a, b fyne.URI) int
	SortFn                  func(a, b fyne.URI) int
	MenuRight               *PopUpMenu
	PathToPasted            string
	Ctx                     = context.Background()
	Right                   *fyne.Container
	Win                     fyne.Window
	RefreshDir              func()
	NextView, PrevView      func(func(string) bool, func(fyne.URI))
	// 显示gif文件
	Gif *fx.AnimatedGif
)

type Me struct {
	SortType int
	SortFn   func(a, b fyne.URI) int
}

func NewMe() *Me {
	Gif = &fx.AnimatedGif{}
	TxtEntry = NewMultiLineEntry()
	Right = ct.NewStack()
	CvsCharSet = cv.NewText("", Red)
	CvsFileSize = cv.NewText("", Red)
	FirstFn = []func(a, b fyne.URI) int{
		DirFirst, FileFirst,
		MeFirst(ExtImage...),
		MeFirst(ExtAudio...),
		MeFirst(ExtVideo...),
		MeFirst(ExtZip...),
	}
	BtnReset = NewButtonWithIcon("", theme.ViewRefreshIcon(), func() {
		SortFn = FirstFn[0]
		SelFilter.SetSelected(OptsFilter[0])
		// 避免刷新2次
		// SelSort.SetSelected(OptsSort[0])
	})
	SelFilter = NewSelect(OptsFilter, func(s string) {
		BdFilterType.Set(s)
	})
	SelSort = NewSelect(OptsSort, func(s string) {
		BdRefreshDir.Set(s)
	})
	SelFilter.SetSelected(OptsFilter[0])
	SelSort.SetSelected(OptsSort[0])
	CvsNum = cv.NewText("", Red)
	CvsMsg = cv.NewText("", Red)
	return &Me{SortFn: DirFirst}
}

func Msg(msg string) {
	go func() {
		for i := 0; i < 3; i++ {
			CvsMsg.Text = ""
			CvsMsg.Refresh()
			time.Sleep(time.Millisecond * 150)
			CvsMsg.Text = msg
			CvsMsg.Refresh()
			time.Sleep(time.Millisecond * 150)
		}
	}()
}
